<template>
  <div class="word-editor-container">
    <div class="toolbar">
      <button @click="uploadFile" class="btn btn-primary">
        <i class="icon-upload"></i>
        上传Word文档
      </button>
      <button @click="downloadFile" class="btn btn-secondary" :disabled="!hasDocument">
        <i class="icon-download"></i>
        下载Word
      </button>
      <button @click="exportToPdf" class="btn btn-secondary" :disabled="!hasDocument">
        <i class="icon-pdf"></i>
        导出PDF
      </button>
      <button @click="printDocument" class="btn btn-secondary" :disabled="!hasDocument">
        <i class="icon-print"></i>
        打印文档
      </button>
      <button @click="saveDocument" class="btn btn-success" :disabled="!hasUnsavedChanges">
        <i class="icon-save"></i>
        {{ hasUnsavedChanges ? '保存更改' : '已保存' }}
      </button>
      <div class="toolbar-divider"></div>
      <button
        @click="reloadDocument()"
        class="btn btn-outline"
        :disabled="!currentFile || loading"
        title="重新转换文档"
      >
        🔄 重新转换
      </button>
    </div>

    <!-- 文档信息栏 -->
    <div v-if="documentInfo" class="document-info">
      <span v-if="isEditing" class="info-item editing"> ✏️ 正在编辑 </span>
      <span v-if="hasUnsavedChanges" class="info-item unsaved"> ● 未保存更改 </span>
    </div>

    <input
      ref="fileInput"
      type="file"
      accept=".docx"
      @change="handleFileUpload"
      style="display: none"
    />

    <div class="editor-wrapper">
      <!-- 错误状态 -->
      <div v-if="hasError" class="error-state">
        <div class="error-icon">❌</div>
        <h3>文档处理失败</h3>
        <p class="error-message">{{ errorMessage }}</p>
        <div class="error-actions">
          <button @click="uploadFile" class="btn btn-primary">重新选择文件</button>
          <button v-if="currentFile" @click="reloadDocument()" class="btn btn-secondary">
            重新转换
          </button>
        </div>
      </div>

      <!-- 文档预览区域 -->
      <div v-else-if="documentHtml" class="document-preview" ref="documentPreview">
        <div
          v-html="documentHtml"
          class="document-content"
          contenteditable="true"
          @input="handleContentChange"
          @blur="handleContentBlur"
          @focus="handleContentFocus"
          ref="editableContent"
        ></div>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-state">
        <div class="empty-icon">📄</div>
        <h3>请上传Word文档开始编辑</h3>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <p>正在处理文档...</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { documentConverter } from '../services/document-converter'
import type { DocumentInfo } from '../types/word-editor'
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas'

// 响应式数据
const fileInput = ref<HTMLInputElement>()
const documentPreview = ref<HTMLElement>()
const editableContent = ref<HTMLElement>()
const documentHtml = ref<string>('')
const loading = ref<boolean>(false)
const currentFile = ref<File | null>(null)
const documentInfo = ref<DocumentInfo | null>(null)
const errorMessage = ref<string>('')
const isEditing = ref<boolean>(false)
const hasUnsavedChanges = ref<boolean>(false)

// 存储编辑内容的变量
let editedContent = ''

// 计算属性
const hasDocument = computed(() => !!documentHtml.value)
const hasError = computed(() => !!errorMessage.value)

/**
 * 触发文件上传
 */
const uploadFile = (): void => {
  fileInput.value?.click()
}

/**
 * 处理文件上传
 */
const handleFileUpload = async (event: Event): Promise<void> => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]

  if (!file) return

  errorMessage.value = ''
  currentFile.value = file
  documentInfo.value = {
    name: file.name,
    size: file.size,
    type: file.type,
    lastModified: file.lastModified,
  }

  loading.value = true

  try {
    const result = await documentConverter.convertDocument(file)

    if (result.success) {
      documentHtml.value = result.html
      const warnings = result.messages.filter((msg) => msg.type === 'warning')
      if (warnings.length > 0) {
        console.warn('文档转换警告:', warnings)
      }
    } else {
      errorMessage.value = result.messages[0]?.message || '文档转换失败'
    }
  } catch (error) {
    console.error('文档处理失败:', error)
    errorMessage.value = error instanceof Error ? error.message : '文档处理失败，请检查文件格式'
  } finally {
    loading.value = false
  }
}

/**
 * 重新加载文档
 */
const reloadDocument = async (): Promise<void> => {
  if (!currentFile.value) return

  errorMessage.value = ''
  loading.value = true

  try {
    const result = await documentConverter.convertDocument(currentFile.value)

    if (result.success) {
      documentHtml.value = result.html
    } else {
      errorMessage.value = result.messages[0]?.message || '文档转换失败'
    }
  } catch (error) {
    errorMessage.value = error instanceof Error ? error.message : '文档重新加载失败'
  } finally {
    loading.value = false
  }
}

/**
 * 获取当前文档内容
 */
const getCurrentContent = (): string => {
  const editorElement = document.querySelector(
    '.document-content[contenteditable="true"]',
  ) as HTMLElement

  if (editorElement && editorElement.innerHTML.trim()) {
    return editorElement.innerHTML
  } else if (editedContent) {
    return editedContent
  }
  return documentHtml.value
}

/**
 * 下载文档
 */
const downloadFile = async (): Promise<void> => {
  if (!currentFile.value) return

  try {
    const {
      Document,
      Packer,
      Paragraph,
      TextRun,
      AlignmentType,
      Table,
      TableRow,
      TableCell,
      WidthType,
      BorderStyle,
    } = await import('docx')

    const currentContent = getCurrentContent()
    if (!currentContent) {
      console.error('没有可下载的内容')
      return
    }

    // 解析HTML并保留样式信息
    const parseHtmlToDocx = (htmlContent: string) => {
      const tempDiv = document.createElement('div')
      tempDiv.innerHTML = htmlContent
      tempDiv.style.cssText = 'position: absolute; left: -9999px; visibility: hidden;'
      document.body.appendChild(tempDiv)

      const paragraphs: any[] = []

      // 样式转换工具函数
      const getComputedStyles = (element: HTMLElement) => {
        const computedStyle = window.getComputedStyle(element)
        return {
          fontSize: computedStyle.fontSize,
          fontFamily: computedStyle.fontFamily,
          fontWeight: computedStyle.fontWeight,
          fontStyle: computedStyle.fontStyle,
          textDecoration: computedStyle.textDecoration,
          color: computedStyle.color,
          textAlign: computedStyle.textAlign,
        }
      }

      const convertFontSize = (fontSize: string): number => {
        if (fontSize.includes('px')) {
          return Math.round(parseFloat(fontSize) * 0.75 * 2)
        } else if (fontSize.includes('pt')) {
          return Math.round(parseFloat(fontSize) * 2)
        } else if (fontSize.includes('em')) {
          return Math.round(parseFloat(fontSize) * 12 * 2)
        }
        return 24
      }

      const convertColor = (color: string): string => {
        if (color.startsWith('rgb')) {
          const matches = color.match(/\d+/g)
          if (matches && matches.length >= 3) {
            const r = parseInt(matches[0]).toString(16).padStart(2, '0')
            const g = parseInt(matches[1]).toString(16).padStart(2, '0')
            const b = parseInt(matches[2]).toString(16).padStart(2, '0')
            return r + g + b
          }
        } else if (color.startsWith('#')) {
          return color.substring(1)
        }
        return '333333'
      }

      const createTextRun = (text: string, element: HTMLElement) => {
        const styles = getComputedStyles(element)
        return new TextRun({
          text,
          font: styles.fontFamily.split(',')[0].replace(/["']/g, '').trim() || 'Times New Roman',
          size: convertFontSize(styles.fontSize),
          color: convertColor(styles.color),
          bold: styles.fontWeight === 'bold' || parseInt(styles.fontWeight) >= 600,
          italics: styles.fontStyle === 'italic',
          underline: styles.textDecoration.includes('underline') ? {} : undefined,
        })
      }

      // 递归解析HTML节点
      const parseNode = (node: Node): any[] => {
        const runs: any[] = []

        if (node.nodeType === Node.TEXT_NODE) {
          const text = node.textContent?.trim()
          if (text && node.parentElement) {
            runs.push(createTextRun(text, node.parentElement))
          }
        } else if (node.nodeType === Node.ELEMENT_NODE) {
          const element = node as HTMLElement
          const tagName = element.tagName.toLowerCase()
          const styles = getComputedStyles(element)

          switch (tagName) {
            case 'p':
            case 'div':
              const childRuns: any[] = []
              for (const child of Array.from(element.childNodes)) {
                childRuns.push(...parseNode(child))
              }
              if (childRuns.length > 0) {
                const alignment =
                  {
                    center: AlignmentType.CENTER,
                    right: AlignmentType.RIGHT,
                    justify: AlignmentType.JUSTIFIED,
                  }[styles.textAlign] || AlignmentType.LEFT

                paragraphs.push(new Paragraph({ children: childRuns, alignment }))
              }
              return []

            case 'br':
              paragraphs.push(new Paragraph({ children: [new TextRun({ text: '', size: 24 })] }))
              return []

            case 'strong':
            case 'b':
            case 'em':
            case 'i':
            case 'u':
              const text = element.textContent?.trim()
              if (text) {
                runs.push(createTextRun(text, element))
              }
              break

            case 'h1':
            case 'h2':
            case 'h3':
            case 'h4':
            case 'h5':
            case 'h6':
              const headingText = element.textContent?.trim()
              if (headingText) {
                const headingRun = createTextRun(headingText, element)
                const alignment =
                  {
                    center: AlignmentType.CENTER,
                    right: AlignmentType.RIGHT,
                    justify: AlignmentType.JUSTIFIED,
                  }[styles.textAlign] || AlignmentType.LEFT

                const headingLevel = parseInt(tagName.charAt(1))
                const spacingBefore = Math.max(240 - (headingLevel - 1) * 40, 120)
                const spacingAfter = Math.max(120 - (headingLevel - 1) * 20, 60)

                paragraphs.push(
                  new Paragraph({
                    children: [headingRun],
                    alignment,
                    spacing: { before: spacingBefore, after: spacingAfter },
                  }),
                )
              }
              return []

            case 'table':
              const tableRows: TableRow[] = []
              const rows = Array.from(element.querySelectorAll('tr'))

              for (const row of rows) {
                const tableCells: TableCell[] = []
                const cells = Array.from(row.querySelectorAll('td, th'))

                for (const cell of cells) {
                  const cellText = cell.textContent?.trim() || ''
                  const cellRun = createTextRun(cellText, cell as HTMLElement)

                  tableCells.push(
                    new TableCell({
                      children: [new Paragraph({ children: [cellRun] })],
                      borders: {
                        top: { style: BorderStyle.SINGLE, size: 1, color: '000000' },
                        bottom: { style: BorderStyle.SINGLE, size: 1, color: '000000' },
                        left: { style: BorderStyle.SINGLE, size: 1, color: '000000' },
                        right: { style: BorderStyle.SINGLE, size: 1, color: '000000' },
                      },
                      width: { size: 100 / cells.length, type: WidthType.PERCENTAGE },
                    }),
                  )
                }

                if (tableCells.length > 0) {
                  tableRows.push(new TableRow({ children: tableCells }))
                }
              }

              if (tableRows.length > 0) {
                paragraphs.push(
                  new Table({
                    rows: tableRows,
                    width: { size: 100, type: WidthType.PERCENTAGE },
                  }) as any,
                )
              }
              return []

            case 'ul':
            case 'ol':
              const listItems = Array.from(element.querySelectorAll('li'))
              listItems.forEach((li, index) => {
                const listItemText = li.textContent?.trim()
                if (listItemText) {
                  const bullet = tagName === 'ul' ? '• ' : `${index + 1}. `
                  const listItemRun = createTextRun(bullet + listItemText, li as HTMLElement)
                  paragraphs.push(
                    new Paragraph({
                      children: [listItemRun],
                      indent: { left: 360 },
                    }),
                  )
                }
              })
              return []

            default:
              for (const child of Array.from(element.childNodes)) {
                runs.push(...parseNode(child))
              }
              break
          }
        }

        return runs
      }

      // 解析所有子节点
      for (const child of Array.from(tempDiv.childNodes)) {
        const runs = parseNode(child)
        if (runs.length > 0) {
          paragraphs.push(new Paragraph({ children: runs }))
        }
      }

      document.body.removeChild(tempDiv)

      if (paragraphs.length === 0) {
        paragraphs.push(
          new Paragraph({
            children: [new TextRun({ text: '文档内容为空', size: 24 })],
          }),
        )
      }

      return paragraphs
    }

    const docParagraphs = parseHtmlToDocx(currentContent)
    const doc = new Document({ sections: [{ properties: {}, children: docParagraphs }] })
    const blob = await Packer.toBlob(doc)

    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = currentFile.value.name.replace(/\.[^.]+$/, '') + '_edited.docx'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)

    console.log('✅ 编辑后的文档下载成功')
  } catch (error) {
    console.error('下载编辑文档失败:', error)
    // 回退到下载原始文件
    try {
      const url = URL.createObjectURL(currentFile.value)
      const a = document.createElement('a')
      a.href = url
      a.download = currentFile.value.name
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
      console.log('⚠️ 已回退到下载原始文件')
    } catch (fallbackError) {
      console.error('下载原始文件也失败了:', fallbackError)
    }
  }
}

/**
 * 创建PDF样式
 */
const createPdfStyles = (): HTMLStyleElement => {
  const styleElement = document.createElement('style')
  styleElement.textContent = `
    .pdf-export-container {
      font-family: 'Times New Roman', serif !important;
      font-size: 12pt !important;
      line-height: 1.6 !important;
      color: #000 !important;
    }
    .pdf-export-container p {
      margin: 0 0 12pt 0 !important;
      text-align: justify !important;
    }
    .pdf-export-container h1, .pdf-export-container h2, .pdf-export-container h3 {
      font-weight: bold !important;
      page-break-after: avoid !important;
    }
    .pdf-export-container h1 { font-size: 18pt !important; margin: 24pt 0 12pt 0 !important; }
    .pdf-export-container h2 { font-size: 16pt !important; margin: 18pt 0 12pt 0 !important; }
    .pdf-export-container h3 { font-size: 14pt !important; margin: 14pt 0 12pt 0 !important; }
    .pdf-export-container table {
      width: 100% !important;
      border-collapse: collapse !important;
      margin: 12pt 0 !important;
      page-break-inside: avoid !important;
    }
    .pdf-export-container th, .pdf-export-container td {
      border: 1pt solid #000 !important;
      padding: 6pt !important;
      text-align: left !important;
      vertical-align: top !important;
    }
    .pdf-export-container th { background-color: #f0f0f0 !important; font-weight: bold !important; }
    .pdf-export-container ul, .pdf-export-container ol {
      margin: 12pt 0 !important;
      padding-left: 24pt !important;
    }
    .pdf-export-container li { margin: 6pt 0 !important; }
    .pdf-export-container img {
      max-width: 100% !important;
      height: auto !important;
      page-break-inside: avoid !important;
    }
    .pdf-export-container u, .pdf-export-container [style*="text-decoration: underline"] {
      text-decoration: underline !important;
    }
    .pdf-export-container strong, .pdf-export-container b, .pdf-export-container [style*="font-weight: bold"] {
      font-weight: bold !important;
    }
    .pdf-export-container em, .pdf-export-container i, .pdf-export-container [style*="font-style: italic"] {
      font-style: italic !important;
    }
    .pdf-export-container s, .pdf-export-container del, .pdf-export-container [style*="text-decoration: line-through"] {
      text-decoration: line-through !important;
    }
    .pdf-export-container a {
      color: #0066cc !important;
      text-decoration: underline !important;
    }
    .pdf-export-container mark {
      background-color: #ffff00 !important;
      color: #000 !important;
      padding: 1pt 2pt !important;
    }
    .pdf-export-container code {
      font-family: 'Courier New', monospace !important;
      background-color: #f5f5f5 !important;
      padding: 2pt 4pt !important;
      border-radius: 2pt !important;
      font-size: 11pt !important;
    }
  `
  return styleElement
}

/**
 * 导出PDF文档
 */
const exportToPdf = async (): Promise<void> => {
  if (!documentHtml.value) {
    alert('没有可导出的内容，请先上传文档')
    return
  }

  try {
    console.log('开始PDF导出流程...')
    const currentContent = getCurrentContent()

    if (!currentContent || currentContent.trim() === '') {
      alert('没有可导出的内容，请先上传文档')
      return
    }

    const pdf = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4' })
    const pageWidth = pdf.internal.pageSize.getWidth()
    const pageHeight = pdf.internal.pageSize.getHeight()
    const margin = 20
    const contentWidth = pageWidth - margin * 2
    const contentHeight = pageHeight - margin * 2

    // 创建临时容器
    const tempContainer = document.createElement('div')
    tempContainer.innerHTML = currentContent
    tempContainer.style.cssText = `
      position: absolute;
      left: -9999px;
      top: 0;
      width: ${contentWidth * 3.78}px;
      padding: 20px;
      background: white;
      box-sizing: border-box;
      overflow: visible;
      word-wrap: break-word;
    `

    const styleElement = createPdfStyles()
    document.head.appendChild(styleElement)
    tempContainer.className = 'pdf-export-container'
    document.body.appendChild(tempContainer)

    // 处理内联样式和超链接
    const elementsWithStyle = tempContainer.querySelectorAll('[style]')
    elementsWithStyle.forEach((element) => {
      const style = element.getAttribute('style')
      if (style) {
        element.setAttribute('style', style + ' !important')
      }
    })

    const links = tempContainer.querySelectorAll('a')
    links.forEach((link) => {
      if (!link.style.color) link.style.color = '#0066cc'
      if (!link.style.textDecoration) link.style.textDecoration = 'underline'
    })

    await new Promise((resolve) => setTimeout(resolve, 200))

    const canvas = await html2canvas(tempContainer, {
      scale: 2,
      useCORS: true,
      allowTaint: false,
      backgroundColor: '#ffffff',
      width: tempContainer.scrollWidth,
      height: tempContainer.scrollHeight,
    })

    // 分页处理
    const pixelsPerMM = (canvas.width / (contentWidth * 3.78)) * 3.78
    const pageHeightInPixels = contentHeight * pixelsPerMM
    let currentY = 0
    let pageCount = 0
    const pageBuffer = 20

    while (currentY < canvas.height) {
      if (pageCount > 0) pdf.addPage()

      const remainingHeight = canvas.height - currentY
      let currentPageHeight = Math.min(pageHeightInPixels - pageBuffer, remainingHeight)

      if (remainingHeight <= pageHeightInPixels) {
        currentPageHeight = remainingHeight
      }

      const pageCanvas = document.createElement('canvas')
      const pageCtx = pageCanvas.getContext('2d')!
      pageCanvas.width = canvas.width
      pageCanvas.height = currentPageHeight

      pageCtx.fillStyle = '#ffffff'
      pageCtx.fillRect(0, 0, canvas.width, currentPageHeight)
      pageCtx.drawImage(
        canvas,
        0,
        currentY,
        canvas.width,
        currentPageHeight,
        0,
        0,
        canvas.width,
        currentPageHeight,
      )

      const imgData = pageCanvas.toDataURL('image/jpeg', 0.95)
      const imgWidth = contentWidth
      const imgHeight = (currentPageHeight / canvas.width) * contentWidth

      pdf.addImage(imgData, 'JPEG', margin, margin, imgWidth, imgHeight)

      if (remainingHeight > pageHeightInPixels) {
        currentY += pageHeightInPixels - pageBuffer
      } else {
        currentY = canvas.height
      }

      pageCount++
      if (pageCount > 50) break
    }

    const filename = `${currentFile.value?.name.replace(/\.[^.]+$/, '') || 'document'}_exported.pdf`
    pdf.save(filename)

    // 清理
    document.body.removeChild(tempContainer)
    document.head.removeChild(styleElement)

    console.log(`✅ PDF导出成功，共 ${pageCount} 页`)
  } catch (error) {
    console.error('PDF导出失败:', error)
    alert(`PDF导出失败: ${error instanceof Error ? error.message : '未知错误'}`)
  }
}

/**
 * 打印文档
 */
const printDocument = (): void => {
  if (!documentHtml.value) return

  const printWindow = window.open('', '_blank')
  if (!printWindow) return

  printWindow.document.write(`
    <!DOCTYPE html>
    <html>
    <head>
      <title>打印文档</title>
      <style>
        body {
          font-family: 'Times New Roman', serif;
          font-size: 12pt;
          line-height: 1.5;
          margin: 2cm;
          color: #000;
        }
        @media print {
          body { margin: 0; padding: 2cm; }
          .no-print { display: none; }
        }
        p { margin: 0 0 12pt 0; }
        table { border-collapse: collapse; width: 100%; }
        table, th, td { border: 1px solid #000; }
        th, td { padding: 4pt 8pt; text-align: left; }
      </style>
    </head>
    <body>
      ${documentHtml.value}
    </body>
    </html>
  `)

  printWindow.document.close()
  printWindow.focus()

  setTimeout(() => {
    printWindow.print()
    printWindow.close()
  }, 500)
}

/**
 * 处理内容变化
 */
const handleContentChange = (event: Event): void => {
  const target = event.target as HTMLElement
  if (target) {
    editedContent = target.innerHTML
    hasUnsavedChanges.value = true
  }
}

/**
 * 处理内容获得焦点
 */
const handleContentFocus = (event: FocusEvent): void => {
  isEditing.value = true
  const target = event.target as HTMLElement
  if (target) {
    target.style.outline = '2px solid #007bff'
    editedContent = target.innerHTML
  }
}

/**
 * 处理内容失去焦点
 */
const handleContentBlur = (event: FocusEvent): void => {
  isEditing.value = false
  const target = event.target as HTMLElement
  if (target) {
    target.style.outline = 'none'
  }
}

/**
 * 保存文档
 */
const saveDocument = (): void => {
  if (!hasUnsavedChanges.value) return

  try {
    if (editedContent) {
      documentHtml.value = editedContent
      console.log('文档内容已保存到内存中')
    }
    hasUnsavedChanges.value = false
    console.log('✅ 文档已保存，可以下载包含编辑内容的文档')
  } catch (error) {
    console.error('保存文档时出错:', error)
  }
}
</script>

<style scoped>
.word-editor-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar-divider {
  width: 1px;
  height: 24px;
  background: #dee2e6;
  margin: 0 8px;
}

.document-info {
  display: flex;
  align-items: center;
  gap: 16px;
  margin: 0 16px 16px 16px;
  padding: 12px 16px;
  background: #e3f2fd;
  border-radius: 6px;
  border-left: 4px solid #2196f3;
  font-size: 14px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.info-item.editing {
  color: #007bff;
  font-weight: 500;
}

.info-item.unsaved {
  color: #dc3545;
  font-weight: 500;
}

.btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background-color: #0056b3;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn-secondary:hover:not(:disabled) {
  background: #545b62;
}

.btn-success {
  background: #28a745;
  color: white;
}

.btn-success:hover:not(:disabled) {
  background: #218838;
}

.btn-outline {
  background: white;
  color: #6c757d;
  border: 1px solid #dee2e6;
}

.btn-outline:hover:not(:disabled) {
  background: #f8f9fa;
  border-color: #adb5bd;
}

.editor-wrapper {
  flex: 1;
  display: flex;
  justify-content: center;
  padding: 20px;
  overflow: auto;
}

.document-preview {
  background-color: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border-radius: 8px;
  max-width: 800px;
  width: 100%;
  min-height: 600px;
}

.document-content {
  padding: 40px;
  font-family: 'Times New Roman', serif;
  font-size: 12pt;
  line-height: 1.5;
  color: #333;
  transition: all 0.2s ease;
  border-radius: 4px;
}

.document-content:focus {
  outline: 2px solid #007bff;
  background: #fafbfc;
}

.document-content[contenteditable='true']:hover {
  background: #f8f9fa;
  cursor: text;
}

/* 文档内容样式 */
.document-content :deep(p) {
  margin: 0 0 12pt 0;
}

.document-content :deep(table) {
  border-collapse: collapse;
  width: 100%;
  margin: 12pt 0;
}

.document-content :deep(table, th, td) {
  border: 1px solid #000;
}

.document-content :deep(th, td) {
  padding: 4pt 8pt;
  text-align: left;
}

.document-content :deep(h1, h2, h3, h4, h5, h6) {
  margin: 18pt 0 12pt 0;
  font-weight: bold;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 60px 20px;
  color: #666;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.empty-state h3 {
  margin: 0 0 12px 0;
  font-size: 24px;
  color: #333;
}

.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 60px 20px;
  color: #dc3545;
}

.error-icon {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.8;
}

.error-state h3 {
  margin: 0 0 12px 0;
  font-size: 24px;
  color: #dc3545;
}

.error-message {
  margin: 0 0 24px 0;
  font-size: 16px;
  color: #6c757d;
  max-width: 500px;
}

.error-actions {
  display: flex;
  gap: 12px;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  z-index: 1000;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-top: 4px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 图标样式 */
.icon-upload::before {
  content: '📤';
}
.icon-download::before {
  content: '📥';
}
.icon-print::before {
  content: '🖨️';
}
</style>
